<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-02-22 10:43:19
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
  <div class="timeSharingCurve">
    <!-- <nu-col :span="24" style="height:calc(130px - 20px);"> -->
    <!-- <nutbTitle title="分时曲线"></nutbTitle> -->
    <NuVerifyForm :model="formData" ref="formData" label-width="90px" class="searchForm" @searchForm="searchForm"
      :buttons="fyButtons">
      <NuformItem label="计量点名称" prop="pointName" :rules="[{ required: true, message: '计量点名称不能为空' }]" width="300px">
        <!-- <el-autocomplete v-model="formData.pointName" :fetch-suggestions="querySearchAsync" placeholder="请输入计量点名称"
          @select="handleSelect"></el-autocomplete> -->
        <el-select v-model="formData.pointName" filterable placeholder="请输入计量点名称">
          <el-option v-for="item in restaurants" :key="item.value" :label="item.value" :value="item.value">
          </el-option>
        </el-select>
      </NuformItem>
      <NuformItem label="电度量名称" prop="meterName" :rules="[{ required: true, message: '电度量名称不能为空' }]" width="300px">
        <nu-input type="text" v-model="formData.meterName" size="middle" placeholder="请输入电度量名称"></nu-input>
      </NuformItem>

      <NuformItem label="日期" prop="type" width="300px">
        <el-date-picker v-model="formData.dataTime" type="date" placeholder="请选择日期" style="width: 100%"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </NuformItem>
      <div class="btnBox">
        <nu-button type="primary" class="searchButton" @click="searchLine">搜索</nu-button>
        <nu-button class="searchButton" @click="clearParams">清除</nu-button>
      </div>
    </NuVerifyForm>
    <div class="line"></div>
    <div style="height: 35px; position: relative; padding: 0 10px" class="renovateTime">
      <nu-button class="searchButton" @click="callBtn">召唤</nu-button>
      <span class="warning_span">当前电量值为表底值（单位:MWH/MVarH）</span>
    </div>
    <!-- </nu-col> -->
    <!-- <nu-col :span="24" style="width:100%;height: calc(100% - 130px - 20px);"> -->
    <div style="height:calc(100vh - 400px);padding:30px 20px 0 20px;">
      <nu-echarts width="auto" height="100%" :option="lineOption" class="echarts" v-if="isEchart"></nu-echarts>
    </div>
    <div>
      <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options" border
        style="margin: 0 0 20px 0">
      </NuTableList>
    </div>
    <!-- </nu-col> -->
  </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import nuEcharts from "@/components/base/echarts";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import * as echarts from "echarts";
import { getDateTime } from "@/utils/ruoyi";
export default {
  name: "timeSharingCurve",
  components: {
    nuCol,
    nutbTitle,
    nuEcharts,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
  },
  data() {
    return {
      formData: {
        pointName: "",
        meterName: "正向有功",
        dataTime: "",
      },
      fyButtons: [],
      isEchart: true,
      lineOption: {
        color: ["#40b0e2", "#69e5c1", "#626b90", "#a0a7e5"],
        title: {
          text: "测点1分时曲线",
          left: "0",
          textStyle: {
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
          name: "MW",
          scale: true,
        },
        grid: {
          left: "3%",
          right: "3%",
        },
        series: [
          {
            data: [],
            type: "line",
            showAllSymbol: true,
            symbolSize: 0,
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(64, 176, 226,0.8)",
                },
                {
                  offset: 1,
                  color: "rgba(64, 176, 226,0.1)",
                },
              ]),
            },
          },
        ],
      },
      dataSource: [],
      columns: [],
      typeList: [
        { label: "测点1", value: 1 },
        { label: "测点2", value: 2 },
        { label: "测点3", value: 3 },
        { label: "测点4", value: 4 },
      ],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        isNoSetHeight: true,
        height: "120px",
      },
      restaurants: []
    };
  },
  created() { },
  mounted() {
    this.formData.dataTime = getDateTime("day");
    this.loadAll();
    // this.setTableColumns()

  },
  methods: {
    /**
     * 查询
     */
    searchLine() {
      this.$refs["formData"].searchForm("form");
    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getTimeSharingLineData();
      }
    },
    /**
     * 召唤
     */
    callBtn() {
      let postData = {
        startDate: this.formData.dataTime,
        endDate: this.formData.dataTime
      }
      this.$httpGet(window.api.callData, postData)
        .then((res) => {
          this.$message({
            message: '开启召唤数据',
            type: 'success'
          })
        })
    },
    /**
     * 清除数据
     */
    clearParams() {
      this.resetForm("formData");
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = "";
        }
      }
    },
    /**
     * 返回输入建议的方法
     * @param {*} queryString
     * @param {*} cb
     */
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 0);
    },
    /**
     * 过滤数据
     * @param {*} queryString
     */
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    /**
     * 点击选中建议项时触发
     * @param {*} item
     */
    handleSelect(item) {
      console.log(item);
    },
    // 远程搜索数据
    async loadAll() {
      let postData = {
        pageSize: 10000,
        page: 1,
      };
      let data = await this.$httpGet(window.api.getMesaNames, postData).then(
        (res) => {
          if (res.code == 200) {
            return res.mesaNames;
          }
        }
      );
      data = await data.map((item) => {
        return { value: item };
      });
      this.restaurants = data;
      this.formData.pointName = data?.[0]?.value
      this.getTimeSharingLineData();
    },
    /**
     * 设置表格头
     */
    setTableColumns() {
      this.columns = [
        {
          label: "",
          prop: "pointName",
          width: "200px",
          fixed: true,
          render: (h, params) => {
            return h("span", params.row.pointName + params.row.mesaName);
          },
        },
      ];
      Array.from({ length: 96 }, (v, i) => {
        var date = new Date("2021-05-01 00:00:00");
        let k = i;
        date.setMinutes(15 * k);
        let d = getDateTime("obj", date);
        this.columns.push({
          label: d.curHours + ":" + d.curMinutes,
          prop: "v" + (k + 1),
        });
      });
    },
    /**
     * 获取曲线数据
     */
    getTimeSharingLineData() {
      if (!(this.formData?.pointName)) {
        return false
      }
      let postData = {
        ...this.formData,
        page: 1,
        pageSize: 1,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      let obj = {};
      this.columns = [];
      this.$httpGet(window.api.getHourEnergyEcharts, postData)
        .then((res) => {
          if (res.code == 200) {
            this.isEchart = false;
            if (res.energyCharts.length) {
              this.columns.push({
                label: "",
                prop: "pointName",
                width: 200,
              });
              res.energyCharts[0].tableDatas.forEach((item, i) => {
                this.columns.push({
                  label: item.time,
                  prop: item.time,
                });
                obj[item.time] = item.energy;
              });
              obj["pointName"] = res.energyCharts[0].pointName;
              this.dataSource = [obj];
              this.lineOption.title.text =
                res.energyCharts[0].pointName +
                res.energyCharts[0].meterName +
                "分时曲线";
              this.lineOption.xAxis.data = res.energyCharts[0].xaxis;

              this.lineOption.series[0].data = res.energyCharts[0].energys;
            } else {
              this.lineOption.xAxis.data = [];
              this.lineOption.series[0].data = [];
              this.dataSource = [];
            }
            this.$nextTick(() => {
              this.isEchart = true;
            });
          } else {
            this.dataSource = [];
          }
        })
        .catch((err) => {
          this.dataSource = [];
        });
    },
  },
};
</script>
    
<style scoped lang="scss">
.timeSharingCurve {
  height: 100%;
}

.searchForm {
  // height: calc(100% - 40px);
  display: flex;
  // align-items: center;
  position: relative;
  flex-wrap: wrap;
  padding-right: 160px;
}

.btnBox {
  display: flex;
  // float: right;
  z-index: 10;
  position: absolute;
  // top: 15px;
  right: 10px;
  margin: 10px 0 0 0;
}

.warning_span {
  font-size: 13px;
  // font-weight: 600;
  color: #F44336;
  margin: 0 10px;
  vertical-align: middle;
}
</style>
    
    